//
//  EpointAttachOpenViewController.m
//  EpointFrame5
//
//  Created by 李亚春 on 14-1-22.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "EpointAttachOpenViewController.h"
#import "EpointIOUtil.h"
#import "EpointBizTools.h"

@interface EpointAttachOpenViewController ()
{
    UIWebView *wv;
    SGdownloader* sgdownload;
    NSString *filePath;
    NSString *dirPath;
}
@end

@implementation EpointAttachOpenViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view
    
    wv = [[UIWebView alloc]initWithFrame:self.getFullContentFrame];
    wv.scalesPageToFit = YES;
    [self.view addSubview:wv];
    
    dirPath = [NSString stringWithFormat:@"%@/Documents/attaches/%@/",NSHomeDirectory(),[self.passParam objectForKey:@"folderguid"]];
    filePath = [NSString stringWithFormat:@"%@%@",dirPath,[self.passParam objectForKey:@"title"]];
    
    NSError *error;
    NSDictionary* dictFile = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error];
    long nFileSize = [dictFile fileSize];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        [EpointIOUtil openTxtFile:filePath withWebView:wv];
    }
    else
    {
        [self showMBPHUDWithMessage:@"正在加载文件..."];
        NSString *fileurl = [self.passParam objectForKey:@"fileurl"];
        fileurl = [EpointBizTools getRealDownloadUrl:fileurl];
        sgdownload = [[SGdownloader alloc]initWithURL:[NSURL URLWithString:fileurl] timeout:20];
        [sgdownload startWithDelegate:self];
    }
    
}

-(void)SGDownloadProgress:(float)progress Percentage:(NSInteger)percentage
{
    
}

-(void)SGDownloadFinished:(NSData*)fileData
{
    [self hideMBPHUD];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];
    
    [fileManager createFileAtPath:filePath contents:fileData attributes:nil];
    
    [EpointIOUtil openTxtFile:filePath withWebView:wv];
}

-(void)SGDownloadFail:(NSError*)error{
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [wv stopLoading];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
